package ca.concordia.soen6011.impl;

import java.util.Date;

import ca.concordia.soen6011.commons.Helpers;
import ca.concordia.soen6011.interfaces.MathFunction;
import ca.concordia.soen6011.Result;

public class TenPowerX implements MathFunction {
	
	private static final double LN10 = 2.302585093;

	
	@Override
	public Result compute(double x, double precision) {
		
		Date start = new Date();
		
		Double answer = null;
		
		
		if (x == 0 ){
			answer = (double) 1;
		} else if (Helpers.isInteger(x)){
			answer = Helpers.power(10, (int) x);
		} else {
			
			// x is a fraction
			double xln10 = x * LN10;
			double expxln10 = exp(xln10, precision);
			answer = expxln10;
		}
		
		Date end = new Date();
		
		// Have to work on this one
		Result result = new Result();
		result.setPrecison(precision);
		result.setComputationTime(end.getTime()-start.getTime());
		result.setOutput(answer);
		return result;
	}

	@Override
	public String getName() {
		return "10 power (x)";
	}
	
	private double exp(double x, double precision) {

		double sum = 1;
		for (int i = 1; ; i++) {
			double term = Helpers.power(x, i) / Helpers.factorial(i);
			if (Helpers.reachedRequiredPrecision(term, precision))
				break;
			else
				sum += term;
			}
		return sum;
	}

	@Override
	public void validate(double x, double precision) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
